import { useOrderedTabs } from "@renderer/queries/hooks/use-tabs";
import { useUIState } from "@renderer/queries/hooks/use-ui";
import type { Tab } from "@shared/triplit/types";
import { useCallback, useEffect, useState } from "react";

const { uiService } = window.service;

export function useActiveTab() {
  const [selectedTab, setSelectedTab] = useState<Tab | null>(null);

  const { data: uiState } = useUIState();
  const { data: orderedTabs = [] } = useOrderedTabs();

  const activeTabId = uiState?.activeTabId || null;
  const activeTabHistory = Array.from(uiState?.activeTabHistory || []);
  const activeTab = orderedTabs.find((t) => t.id === activeTabId);

  const setActiveTabId = useCallback(async (tabId: string) => {
    await uiService.updateActiveTabId(tabId);
    await uiService.updateActiveTabHistory(tabId);
  }, []);

  useEffect(() => {
    if (!activeTabId || !activeTab) {
      setSelectedTab(null);
      return;
    }

    setSelectedTab(activeTab || null);
  }, [activeTabId, activeTab]);

  return {
    selectedTab,
    activeTab,
    activeTabId,
    activeTabHistory,
    tabs: orderedTabs,
    setActiveTabId,
  };
}
